var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var Data = require('../../utils/data.js');
var common = require("../../utils/common.js")
var utils = require("../../utils/util.js");
var WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
var page_size = 5,
  page = 1,
  keyword = '',
  that, animation;
var currentExchangeBall;
var currentExchangeBallArray = [];

var energy_full = 500;
var energy;
var energy_percent;
var progress;

// var share = function(that){
// 	 animation.scale(1).step()
// 	 animation.scale(0.9).step()
// 	 animation.scale(1).step()
// 	 animation.scale(0.9).step() 
// 	 that.setData({ animation: animation.export() })
// }

// var apple = function(that){
// 	animation.translateY(-4).step()
//     animation.translateY(0).step()
//     that.setData({ animationapple: animation.export() })
// }

/**
 * 判断进度条的位置
 */
function ballGrogress($this) {
  energy = $this.data.energy;
  //energy_percent = energy / energy_full;
  energy_percent = parseInt((energy / energy_full) * 100);
  if (energy_percent > 100) {
    energy_percent = 100;
  } else if (energy_percent < 0) {
    energy_percent = 0;
  }
  progress = $this.data.progress;
  $this.setData({
    progress: energy_percent / 100
  })
  if (that.data.progress == 1) {
    $this.setData({
      isKick: false,
      hidePercent: true,
      canServe: true
    })
  } else {
    $this.setData({
      isKick: true,
      hidePercent: false,
      canServe: false
    })
  }
}

//获取步数
var getData = function (that) {
  wx.getSetting({
    success: function (res) {
      //console.log(res);
      /*if (!res.authSetting['scope.werun']) {
	    		 common.showInfo('获取微信运动步数，需要开启计步权限',
	    		     function(res){
	    			 	if(res.confirm){
	    			 		// 跳转去设置
	    			 		 //wx.openSetting({
	    		              //   success: function (res) {
	    		              //   }
	    		             //})
	    			 		
	    			 		//wx.redirectTo({
	    			 		//	url:'../step/step'
	    			 		//})
	    			 	}else{
	    			 		// 不设置
	    			 	}
	    		     },
	    		     true
	    		 )  
	        
	    	 } else {*/
      common.wxshowLoading();

      wx.getWeRunData({
        success: function (res) {
          common.wxhideLoading();
          var encryptedData = res.encryptedData;
          var iv = res.iv;
          var appid = 'wx7ded460b47030cb2';
          var session_key = common.getStorage('session_key');
          // 使用解密工具，链接地址：
          // https://codeload.github.com/gwjjeff/cryptojs/zip/master
          var pc = new WXBizDataCrypt(appid, session_key);
          var data = pc.decryptData(encryptedData, iv)
          var curStep = data.stepInfoList[30].step

          // 当前步数
          that.setData({
            curStorageStep: curStep
          })
          // 判断是否已经点击过发球
          if (utils.isBlank(wx.getStorageSync("currentExchangeBall").toString()) &&
            utils.isBlank(wx.getStorageSync("currentExchangeBallArray").toString())) {
            that.setData({
              currentUsableStep: 1111
            })
          } else {
            // 已经发过球
            var currentExchangeBallArray = wx.getStorageSync("currentExchangeBallArray");
            /*if (!utils.isBlank(currentExchangeBallArray)) {
              
              // 当前小时数
              var currentHour = utils.formatTime(new Date()).split(" ")[1].split(":")[0];
              // 当前分钟数
              var currentMunite = utils.formatTime(new Date()).split(" ")[1].split(":")[1];
              // 当前球小时数
              var currentBallHour = currentExchangeBallArray[0].ballTime.split(" ")[1].split(":")[0];
              // 当前球分钟数
              var currentBallMunite = currentExchangeBallArray[0].ballTime.split(" ")[1].split(":")[1];
              if (currentHour - currentBallHour == 1) {
                // 小时相等，判断分钟数
                if (currentMunite - currentBallMunite <= 0) {
                  // 时间到，显示射门 ,1小时
                  that.setData({
                    hideCount:false,
                    shootText:"射门"
                  })
                } else {
                  // 时间没到，显示剩余时间
                  currentExchangeBallArray[0].count = 1;
                }
              } else {
                // 时间没到，显示剩余时间 
               currentExchangeBallArray[0].count = 1 - (currentHour - currentBallHour);
              }
            }*/
            that.setData({
              currentUsableStep: 1111,
              ballList: currentExchangeBallArray
            })
          }

          that.data.energy = that.data.currentUsableStep;
          ballGrogress(that);
          Data.httpGet({
            action: 'setEnergy',
            energy: curStep
          },
            function (res) {
              that.setData({
                stepnum: curStep,
                stepstatus: 1
              })
              //获取能量
              Data.httpGet({
                action: 'getEnergy',
                stepMinus: 1,
                account_id: common.getStorage('user_id')
              },
                function (res) {
                  var status = res.data.status
                  if (status == 'y') {
                    that.setData({
                      imgHidden: true,
                      imgHiddenInitEjoy: false
                    })
                  } else {
                    that.setData({
                      imgHidden: false,
                      imgHiddenInitEjoy: true
                    })
                  }
                }
              );
              // 

            }
          );

        },
        fail: function (res) {
          common.wxhideLoading();
          wx.showModal({
            title: '提示',
            content: '开发者未开通微信运动，请关注“微信运动”公众号后重试',
            showCancel: false,
            confirmText: '知道了'
          })
        }
      })
    }
    //}
  })
}

//球
var GetList = function (that) {
  common.wxshowLoading();
  Data.httpGet({
    action: 'getBall',
    page_size: page_size,
    page: 1,
    account_id: common.getStorage('user_id')
  },
    function (res) {
      var l = that.data.list;
      if (l.length >= res.data.source.recordCount) {
        common.wxhideLoading();
        return false;
      }
      var res = res.data;
      for (var i = 0; i < res.data.length; i++) {
        if (res.data[i]['hourminus'] >= app.globalData.globalhour) {
          res.data[i]['showinfo'] = '接个球';
          res.data[i]['status'] = '1';
        } else {
          var hourminus = app.globalData.globalhour - res.data[i]['hourminus'];
          res.data[i]['showinfo'] = '剩' + hourminus + '秒';
          res.data[i]['status'] = '0';
        }
        l.push(res.data[i])
      }
      that.setData({
        list: l
      });
      common.wxhideLoading();
    }
  );
}

//动态
var GetListNews = function (that) {
  common.wxshowLoading();
  Data.httpGet({
    action: 'getBalance',
    page_size: 5,
    page: 1,
    isToday: 1,
    account_id: common.getStorage('user_id')
  },
    function (res) {
      var l = that.data.listnews;
      if (l.length >= res.data.source.recordCount) {
        common.wxhideLoading();
        return false;
      }
      var res = res.data;
      for (var i = 0; i < res.data.length; i++) {
        l.push(res.data[i])
      }
      that.setData({
        listnews: l
      });
      common.wxhideLoading();
    }
  );
}

//达人榜
var GetListRank = function (that) {
  common.wxshowLoading();
  Data.httpGet({
    action: 'getAccountInfoList',
    page_size: 10,
    page: 1,
    ora_quantity: 1
  },
    function (res) {
      var l = that.data.listrank;
      if (l.length >= res.data.source.recordCount) {
        common.wxhideLoading();
        return false;
      }
      var res = res.data;
      for (var i = 0; i < res.data.length; i++) {
        l.push(res.data[i])
      }
      that.setData({
        listrank: l
      });
      common.wxhideLoading();
    }
  );
}

//检查用户信息 
var checkUserInfo = function (that) {
  wx.getSetting({
    success: function (res) {
      if (res.authSetting['scope.userInfo']) {
        Data.httpGet({
          action: 'checkUserInfo',
          open_id: common.getStorage('openid')
        },
          function (res) {
            if (res.data.account_id != 0) {
              common.setStorage('user_id', res.data.account_id);
              getData(that);
            } else {
              wx.navigateTo({
                url: '../register/register?invite_code=' + that.data.invite_code
              })
            }
          }
        );
      } else {
        wx.navigateTo({
          url: '../register/register'
        })
      }
    },
    fail: function (res) {
      console.log(res)
    }
  })
}

Page({
  data: {
    list: [],
    listnews: [],
    listrank: [],
    imgHiddenInitEjoy: true,
    imgHidden: true,
    stepnum: 0,
    stepstatus: 0,
    // by lianli
    ballList: [],
    storeBallList: [],
    energy: 0,
    isKick: true,
    hidePercent: false,
    canServe: false,
    hideGold: true,
    left1: Math.floor(Math.random() * 105 + 1),
    left2: Math.floor(Math.random() * 200 + 1),
    left3: -(Math.floor(Math.random() * 200 + 1)),
    left4: Math.floor(Math.random() * 200 + 1),
    left5: -(Math.floor(Math.random() * 200 + 1)),
    left6: Math.floor(Math.random() * 200),
    left7: -(Math.floor(Math.random() * 200 + 1)),
    left8: Math.floor(Math.random() * 200 + 1),
    curStorageStep: 0, // 当前步数
    currentUsableStep: 11110 // 当前可用于兑换的步数
  },
  onLoad(e) {
    that = this;
    if (e.invite_code) {
      that.setData({
        invite_code: e.invite_code ? e.invite_code : ''
      }, function () {
        checkUserInfo(that);
      })
    } else {
      checkUserInfo(that);
    }

    animation = wx.createAnimation();
    // Data.autoLogin();
    common.showShareMenu();

    //  setInterval(share,2000,that);
    //  setInterval(apple,2000,that);

    //by lianli:
    //能量条：
    var energy_full = 500;
    var energy = this.data.energy;
    var energy_percent = energy / energy_full;
    var progress = this.data.progress;
    this.setData({
      progress: energy_percent
    })
    if (energy_percent == 1) {
      this.setData({
        ballShow: false,
        isKick: false, //是否隐藏‘开球’
        hidePercent: true,
        canServe: true
      })
    }
  },
  toEngeryPage: function () {
    wx.navigateTo({
      url: '../energy/energy',
    })
  },
  onShareAppMessage: function (res) {
    return {
      title: '对不起~打扰了，我就想请你来亿享~',
      path: '/pages/index/index?invite_code=' + common.getStorage("invite_code")
    }
  },
  onShow: function () {
    page = 1;
    checkUserInfo(that);
    that.setData({
      list: [],
      listnews: [],
      listrank: [],
    });
    GetList(that);
    GetListNews(that);
    GetListRank(that);

    this.startGame();

  },
  //发球
  generate: function () {
    // by lianli
    var canServer = this.data.canServe;
    //是否可以以发球（能量未满不能发球）
    if (canServer) {
      // 创建球：
      var ballList = this.data.ballList;
      var ballObject = {
        left: 0,
        top: 0,
        count: 60,
        hideCount: true,
        shootTime: 60,
        canShoot: false,
        shooting: false,
        speed: 3,
        rotate: true, //旋转
        vibrate: false, //是否上下震动
        shootText: "",
        hideText: true,
        ballTime: utils.formatTime(new Date())
      };
      ballList.push(ballObject);

      // wx.setStorageSync("currentExchangeBallArray", that.data.storeBallList);

      // Data.httpGet({
      //   action: 'setEnergy',
      //   stepMinus: 1,
      //   account_id: common.getStorage('user_id')
      // },
      //   function (res) {
      //     var x_axis = parseInt(common.getRandom(10, 150));
      //     var y_axis = parseInt(common.getRandom(10, 90));
      //     Data.httpGet({
      //       action: 'setBall',
      //       stepMinus: 1,
      //       x_axis: x_axis,
      //       y_axis: y_axis
      //     },
      //       function (res) {

      //         wx.setStorageSync("currentExchangeBall", that.data.curStorageStep);
      //         common.wxhideLoading();
      //         page = 1;
      //         that.setData({
      //           list: [],
      //           imgHidden: false,
      //           imgHiddenInitEjoy: true
      //         });
      //         GetList(that);
      //         getData(that);
      //       }
      //     );
      //   }
      // );

    } else {
      common.showError('能量不足，攒攒再过来吧~');
      return false;
    }

    if (that.data.stepstatus == 0) {
      common.showError('正在读取微信步数，请稍后');
      return false;
    }
    common.wxshowLoading();
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },
  scale: function () {
    share(that)
  },

  translate: function () {
    apple(that)
  },

  //获取步数
  getStep: function () {
    getData(that)
  },
  //能量不足
  energyNotEnough: function () {
    common.showError('能量不足，攒攒再过来吧~');
    return false;
  },

  //点击小足球获取能量币
  setBalance: function (e) {
    var id = e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;
    if (status == 0) {
      common.showError('时间还没到哦~');
      return false;
    }
    var rand = common.getRandom(1, 100);

    rand1 = rand;
    Data.httpGet({
      action: 'setBall',
      id: id,
      ball_status: 1
    },
      function (res) {
        if (res.data.status == 'y') {
          Data.httpGet({
            action: 'setBalance',
            ball_id: id,
            ejoy: rand
          },
            function (res) {
              if (res.data.status == 'y') {
                common.showInfo('恭喜您获得' + (rand1 / 100).toFixed(2) + 'Ejoy币');
                page = 1;
                that.setData({
                  list: [],
                });
                GetList(that);
                getData(that);
                GetListNews(that);
              } else {
                common.showError(res.data.info);
              }
            }
          );
        } else {
          common.showError(res.data.info);
        }

      }
    );
  },
  startGame() {
    this.gaming = true;
    requestAnimationFrame(this.animate);
  },

  animate() {
    var _this = this;
    var random_num = Math.random() + 1.1;
    var speed = 2;
    var ballList = _this.data.ballList;

    var newBallList = [];
    for (var i = 0; i < ballList.length; i++) {

      var ballItem = {
        left: ballList[i].left,
        top: ballList[i].top,
        count: ballList[i].count,
        hideCounthideCount: ballList[i].hideCount,
        shootTime: ballList[i].shootTime,
        canShoot: ballList[i].canShoot,
        shooting: ballList[i].shooting,
        speed: ballList[i].speed,
        rotate: ballList[i].rotate,
        vibrate: ballList[i].vibrate,
        shootText: ballList[i].shootText,
        hideText: ballList[i].hideText,
        ballTime: ballList[i].ballTime,
      };

      var newLeft = ballList[i].left - ballList[i].speed * (random_num + i / 2);
      var newTop = ballList[i].top - speed * random_num;
  
      // 判断球top值>指定值？停止运动 ：继续修改left,top值
      if (ballList[i].top <= -400) {

        if (ballList[i].count <= 0) {
          ballItem.canShoot = true;
          ballItem.hideCount = true;
          ballItem.shootText = "射门"
        } else {
          ballItem.rotate = false;
          ballItem.vibrate = true;
          ballItem.hideText = false;
          ballItem.hideCount = false;
        }
      } else {
        ballItem.left = newLeft;
        ballItem.top = newTop;
      };

      if (ballList[i].left <= -400) {
        ballItem.speed = -3;
        ballItem.left =newLeft;
        ballItem.top = newTop;
      }
      if (ballList[i].left >= 250) {
        ballItem.speed = 3;
        ballItem.left = newLeft;
        ballItem.top = newTop;
      }
      // 球是否在射击运行中 ,判断射击倒计时<=0 ? 删除球 ：减倒计时
      if (ballList[i].shooting) {
        var shootTime = "ballList[" + i + "].shootTime";
        var s_time = ballList[i].shootTime;
        if (s_time <= 0) {
        
        } else {
          ballItem.shootTime=s_time - 1;
          newBallList.push(ballItem);
        }
      }else{
        newBallList.push(ballItem);
      }
    }

    this.setData({
      ballList:newBallList
    })
    if (this.gaming) {
      requestAnimationFrame(this.animate);
    }
  },

  //点击射门
  shoot: function (e) {
    var _this = this;
    var canShoot = e.currentTarget.dataset.canshoot;
    var idx = e.currentTarget.dataset.idx;
    var shooting = "ballList[" + idx + "].shooting";
    var vibrate = "ballList[" + idx + "].vibrate";
    var hideText = "ballList[" + idx + "].hideText";
    if (canShoot == true) {
      _this.setData({
        [shooting]: true,
        [vibrate]: false,
        [hideText]: true
      });
    }
  },
  onHide: function () {
    clearInterval(this.gameTimer);
  }
})